package com.service.schedule;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.sql.visitor.functions.Concat;
import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.dao.schedule.JobDao;
import com.model.schedule.JobModel;
import com.service.schedule.util.ScheduleUtils;

@Service
public class JobService {
	static final Logger logger = LoggerFactory.getLogger(JobService.class);

	@Autowired
	private Scheduler scheduler;
	@Autowired
	JobDao jobDao;

	@PostConstruct
	public void init() {
//		HashMap<String, Object> hashMap = new HashMap<String, Object>();
//		hashMap.put("status", "1");
//		List<JobModel> scheduleJobList = jobDao.selectList(hashMap);
//		for (JobModel scheduleJob : scheduleJobList) {
//			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
//			// 如果不存在，则创建
//			if (cronTrigger == null) {
//				ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
//			} else {
//				ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
//			}
//		}
	}

	/**
	 * @return void
	 * @author chengpunan
	 * @desc 立即执行定时任务
	 * @date 2020/11/13 15:32
	 * @params [jobId]
	 **/
	public HttpResult run(String jobId) {
		String reString = ScheduleUtils.run(scheduler, jobDao.load(jobId));
		if (StringUtils.isNullOrEmpty(reString)) {
			return HttpResult.ok();
		} else {
			return HttpResult.error(reString);
		}
	}

	@Transactional
	public HttpResult pause(JobModel jobModel) {
		ScheduleUtils.pauseJob(scheduler, jobModel.getJobId());
		HttpResult httpResult = new HttpResult();
		jobModel.setRunStatus(Global.NO);
		jobModel.setStatus(Global.NO);
		int result = jobDao.update(jobModel);
		if (result > 0) {
			httpResult.setMsg("保存成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败！");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult resumeJob(JobModel jobModel) {
		ScheduleUtils.resumeJob(scheduler, jobModel.getJobId());
		HttpResult httpResult = new HttpResult();
		jobModel.setRunStatus(Global.YES);
		jobModel.setStatus(Global.YES);
		int result = jobDao.update(jobModel);
		if (result > 0) {
			httpResult.setMsg("保存成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败！");
		}
		return httpResult;
	}

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<JobModel> list = jobDao.selectList(queryMap);
		int count = jobDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String jobId) {
		HttpResult httpResult = new HttpResult();
		JobModel jobModel = jobDao.load(jobId);
		httpResult.setData(jobModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult save(JobModel jobModel) {
		if (jobModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		jobModel.setRunStatus(Global.NO);
		if (!StringUtils.isNotNull(jobModel.getJobId())) {
			Integer countInteger = jobDao.getTableCount();
			jobModel.setJobId((countInteger + 1) + "");
			result = jobDao.insert(jobModel);
		} else {
			result = jobDao.update(jobModel);
		}
		if (jobModel.getStatus() == 1) {
			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, jobModel.getJobId());
			// 如果不存在，则创建
			if (cronTrigger == null) {
				ScheduleUtils.createScheduleJob(scheduler, jobModel);
			} else {
				ScheduleUtils.updateScheduleJob(scheduler, jobModel);
			}
		} else {
			ScheduleUtils.deleteScheduleJob(scheduler, jobModel.getJobId());
		}
		if (result > 0) {
			httpResult.setMsg("保存成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败！");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult delete(String jobId) {
		//
		ScheduleUtils.deleteScheduleJob(scheduler, jobId);
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(jobId)) {
			return HttpResult.error("参数不能为空");
		}
		int result = jobDao.delete(jobId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<JobModel> list = jobDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), JobModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
